<template>
  <h1>轮播图列表</h1>
  <el-table :data="bannerlist" style="width: 100%" >
    <el-table-column prop="bannerid" label="轮播图编号" width="180" />
    <el-table-column label="图片" width="180">
      <template #default="scope">
        <img class="img" :src="scope.row.img" />
      </template>
    </el-table-column>
    <el-table-column prop="alt" label="图片提示" width="180" />
    <el-table-column prop="link" label="图片链接" width="180" />
    <el-table-column label="是否启用" width="180">
      <template #default="scope">
        <el-switch v-model="scope.row.flag" @change="(val: boolean) => updateBannerFlag(scope.row.bannerid, val)" />
      </template>
    </el-table-column>

    <el-table-column label="操作">
      <template #default="scope">
        <el-popconfirm title="你确定要删除吗?" @confirm="deletebannerlist(scope.row.bannerid)">
          <template #reference>
            <el-button type="danger" :icon="Delete" circle />
          </template>
        </el-popconfirm>

      </template>
    </el-table-column>
  </el-table>
</template>

<script setup lang="ts">
// 插件
import {
  Delete,
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';
import 'element-plus/dist/index.css'
import { reactive, ref } from "vue";
import service from "../../../ulit/service";
const loding = ref(true)
interface IBanner {
  link: string,
  img: string,
  alt: string,
  bannerid: string,
  flag: boolean
}

// 1、定义轮播图数据
let bannerlist = reactive<IBanner[]>([]);
// 2、获取所有的轮播图数据
const getbannerlist = () => {
  service({
    url: "/banner/list"
  })
    .then((res: any) => {
      if (res.data.code === "200") {
        // bannerlist = res.data.data;
        bannerlist.length = 0
        bannerlist.push(...res.data.data);
      }
    })
}

// 3、更新轮播图的访问状态
const updateBannerFlag = (bannerid: string, val: boolean) => {
  service({
    url: "/banner/updateFlag",
    method: 'post',
    data: {
      bannerid: bannerid,
      flag: val
    }
  }).then(res => {
    if (res.data.code === "200") {
      // alert("更新成功");
      ElMessage({
        message: '更新成功',
        type: 'success',
      })
    }
  })
}
getbannerlist();

//4.删除
const deletebannerlist = (bannerid: string) => {
  service({
    url: "banner/delete",
    params: {
      bannerid
    }
  }).then(res => {
    if (res.data.code === "200") {
      ElMessage({
        message: '删除成功',
        type: 'success',
      })
      // 删除成功后，两种做法：
      // 1、重新发送请求获取最新数据：缺点是多发了一次请求。
      getbannerlist()
      // 2、删除前端的数组。缺点：如果多人同时操作数据，那么，就看不到别人删除的数据
      // let index = bannerlist.findIndex(item => item.bannerid == bannerid)
      // bannerlist.splice(index, 1)
    }
  })
}

</script>

<style scoped>
.img {
  width: 200px;
  height: 150px;
}
</style>